<template>
  <div class="container">
    <div class="common-header-wrap">
      <mt-header class="common-header" title="登录">
        <mt-button icon="back" slot="left" @click="$router.go(-2)"></mt-button>
        <mt-button slot="right" @click="onSignup">注册</mt-button>
      </mt-header>
    </div>

    <div class="top-wrapper">
      <mt-field class="input-wrapper" v-model="username" placeholder="邮箱/手机号" type="text"> </mt-field>
      <mt-field class="input-wrapper" v-if="login_type == '1'" type="password" v-model="password" placeholder="请输入密码"> </mt-field>
      <mt-field class="input-wrapper" v-if="login_type == '2'" type="text" v-model="verifyCodeMobile" placeholder="请输入验证码">
        <mt-button @click="sendVerifyCodeMobile" class="countdown" type="default" size="small" plain>{{ sendStateTextMobile }}</mt-button>
      </mt-field>
    </div>
    <mt-button type="primary" class="ds-button-large mt-20 mb-10" v-on:click="signin">登录</mt-button>
    <div class="retrieve-wrapper">
      <!-- <template>
        <div class="retrieve-item" @click="switchLoginType(2)" v-if="login_type == 1">
          <label id="retrieve-title">验证码登录</label>
        </div>
        <div class="retrieve-item" @click="switchLoginType(1)" v-if="login_type == 2">
          <label id="retrieve-title">账号密码登录</label>
        </div>
      </template> -->
      <div></div>
      <div class="retrieve-item" @click="onRetrieve">
        <label id="retrieve-title">忘记密码？</label>
      </div>
    </div>
    <!--        <div class="third-login">-->
    <!--            <div class="third-title">第三方登录</div>-->

    <!--        </div>-->
    <!-- && hideshow && sessionStorage -->
    <div class="bottom-wrapper" v-if="isShowWechat && hideshow && sessionStorage">
      <div class="auth-title-wrapper">
        <div class="auth-line"></div>
        <label class="auth-title">第三方登录</label>
        <div class="auth-line"></div>
      </div>
      <div v-if="isShowWechat" class="auth-bottom-wrapper">
        <div class="wx-login" @click="onWechat">
          <img class="wx-img" src="../../../assets/image/home/wx.png" />
          <div class="wx-title">微信</div>
        </div>
        <!--                        <div class="auth-item" v-if="isShowWechat" @click="onWechat">-->
        <!--                            <i class="auth-item-icon iconfont wechat">&#xe647;</i>-->
        <!--                            <label class="auth-title auth-item-title">微信</label>-->
        <!--                        </div>-->
        <!--                        <div class="auth-item" v-if="isShowSina" @click="onSina">-->
        <!--                            <i class="auth-item-icon iconfont sina">&#xe646;</i>-->
        <!--                            <label class="auth-title auth-item-title">微博</label>-->
        <!--                        </div>-->
        <!--                        <div class="auth-item" v-if="isShowQQ" @click="onTencent">-->
        <!--                            <i class="auth-item-icon iconfont tencent">&#xe882;</i>-->
        <!--                            <label class="auth-title auth-item-title">QQ</label>-->
        <!--                        </div>-->
      </div>
    </div>
  </div>
</template>

<script>
import { login, wechatLogin, wechatJump, smsLogin } from '../../../api/memberLogin';
import { getSmsCaptcha } from '../../../api/common';
import { getMemberInfo } from '../../../api/member';
import { isWechat } from '../../../util/wechat';
import { Indicator, Toast } from 'mint-ui';
import { mapMutations, mapActions, mapState } from 'vuex';

export default {
  name: 'Login',
  data() {
    return {
      sessionStorage:true,
      username: '',
      password: '',
      verifyCodeMobile: '',
      token: '',
      login_type: 1,
      canSendMobile: true,
      timeIntervalMobile: false,
      sendStateTextMobile: '发送',
      docmHeight: document.documentElement.clientHeight ||document.body.clientHeight,
      showHeight: document.documentElement.clientHeight ||document.body.clientHeight,
      hideshow:true ,//显示或者隐藏footer
      isWechat:false,
    };
  },
  watch: {
    //监听显示高度
  //  showHeight:function() {
  //    console.log(this.docmHeight);
  //    console.log(this.showHeight)
  //    if(this.docmHeight > this.showHeight){
  //     //隐藏
  //      this.hideshow=false
  //    }else{
  //     //显示
  //      this.hideshow=true
  //    }
  //  }
 },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // 通过 `vm` 访问组件实例
      if (from.fullPath == '/member/seller_joinin_1') {
        vm.utils.setCookie('referrer1', encodeURIComponent(from.fullPath), 1 / 24);
      }
      vm.utils.setCookie('referrer', encodeURIComponent(from.fullPath), 1 / 24);
    });
  },
  computed: {
    ...mapState({
      inviter_id: (state) => state.member.inviterId,
      config: (state) => state.config.config,
    }),
    isShowWechat: function() {
      // this.isWechat = isWechat()
      if ((isWechat() || this.isWechat) && this.config && this.config.weixin_isuse == 1) {
        return true;
      }
      return false;
    },
    isShowSina: function() {
      if (!isWechat() && this.config && this.config.sina_isuse == 1) {
        return true;
      }
      return false;
    },
    isShowQQ: function() {
      if (!isWechat() && this.config && this.config.qq_isuse == 1) {
        return true;
      }
      return false;
    },
  },
  created: function() {
    console.log(this.docmHeight)
    console.log(this.showHeight)

    !sessionStorage.getItem("jurisdiction");
    Indicator.close();
    let user_info = this.utils.getCookie('user_info');
    let token = this.utils.getCookie('key');
    if (user_info) {
      user_info = JSON.parse(decodeURIComponent(user_info));
      this.saveAuthInfo({ token: token, info: user_info });
      this.utils.clearCookie('user_info');
      this.utils.clearCookie('key');
      this.goHome();
    }
    if (this.$route.query.clear) {
      this.memberLogout();
    }
    if (this.$route.query.token) {
      this.getmemberinformation({ token: this.$route.query.token }).then(() => {
        // this.$router.push({name:'MemberIndex'})
        this.goHome();
      });
      return;
    }
    this.fetchConfig({}).then(
      (response) => {},
      (error) => {
        Toast(error.message);
      }
    );
  },
  mounted() {
     window.onresize = ()=>{
     return(()=>{
       this.showHeight = document.documentElement.clientHeight || document.body.clientHeight;
   })()
   }
    let isTokenInvalid = this.$route.params.isTokenInvalid;
    if (isTokenInvalid) {
      Toast('登录过期');
    }
    this.$nextTick(()=>{
      this.isWechat = isWechat()
    })
  },
  methods: {
    ...mapMutations({
      saveAuthInfo: 'memberLogin',
      saveSellerAuthInfo: 'sellerLogin',
      memberLogout: 'memberLogout',
      memberToken: 'memberToken',
    }),
    ...mapActions({
      fetchConfig: 'fetchConfig',
      getmemberinformation: 'getmemberinformation',
    }),
    onTencent() {
      window.location.href = env.API_HOST + '/api/oa_qq';
    },
    onSina() {
      window.location.href = env.API_HOST + '/api/oa_sina';
    },
    loginSuccess(response) {
      Indicator.close();
      this.saveAuthInfo({ token: response.result.token, info: response.result.info });
      if (response.result.seller_info) {
        this.saveSellerAuthInfo({
          token: response.result.seller_token,
          info: response.result.seller_info,
        });
      }
      this.goHome();
    },
    signin() {
      let username = this.username;
      let password = this.password;
      if (username.length === 0) {
        Toast('请输入用户名/邮箱/手机号');
        return;
      }
      // TODO: 用户名（为手机号或邮箱）校验

      if (this.login_type == 1) {
        if (password.length === 0) {
          Toast('请输入密码');
          return;
        }
        if (password.length < 6) {
          Toast('至少输入6位密码');
          return;
        }
        Indicator.open();
        login(username, password).then(
          (response) => {
            this.loginSuccess(response);
          },
          (error) => {
            Indicator.close();
            Toast(error.message);
          }
        );
      } else {
        Indicator.open();
        smsLogin({ usermobile: this.username, mobilecode: this.verifyCodeMobile }).then(
          (response) => {
            this.loginSuccess(response);
          },
          (error) => {
            Indicator.close();
            Toast(error.message);
          }
        );
        // smsLogin({ usermobile: this.username, mobilecode: this.verifyCodeMobile }).then((res) => {
        //   Indicator.close();
        //   this.saveAuthInfo({ token: res.result.token, info: res.result.info });
        //   if (response.result.seller_info) {
        //     this.saveSellerAuthInfo({
        //       token: res.result.seller_token,
        //       info: res.result.seller_info,
        //     });
        //   }
        //   this.goHome();
        // });
      }
    },

    goBack() {
      let isFromInfoEdit = this.$route.params.isFromInfoEdit;
      let isFromShare = this.$route.params.isFromShare;
      if (isFromInfoEdit || isFromShare) {
        this.$router.push('home');
      } else {
        this.$router.go(-1);
      }
    },

    goHome() {
        // let preservation = ['/home/memberlogin','/member/setting'];
        // let referrer = this.utils.getCookie('referrer');
        // console.log(referrer)
        // if(referrer){
        //   for(var i = 0; i < preservation.length; i++){
        //     console.log(preservation[i])
        //     if(preservation[i].indexOf(referrer) >= 0){
        //       this.$router.push({ name: 'HomeIndex' });
        //     }else{
        //       console.log(1)
        //       this.utils.clearCookie('referrer');
        //       this.$router.push({ path: referrer });
        //     }
        //   }
        // }else{
        //   console.log(2)
        //    this.$router.push({ name: 'HomeIndex' });
        // }
      let referrer = this.utils.getCookie('referrer');
      if (referrer) {
        // 返回之前的页面
        referrer = decodeURIComponent(referrer);
        if (referrer == '/home/memberlogin') {
          this.$router.push({ name: 'MemberIndex' });
        }else if(referrer == '/member/setting'){
          this.$router.push({ name: 'HomeIndex' });
        }else {
          this.utils.clearCookie('referrer');
          this.$router.push({ path: referrer });
        }
      } else {
        this.$router.push({ name: 'HomeIndex' });
      }
    },

    onSignup() {
      this.$router.push({ name: 'HomeMemberRegister' });
    },

    onRetrieve() {
      this.$router.push({ name: 'HomeMemberForget' });
    },

    //获取微信code链接
    onWechat() {
      let link = encodeURIComponent(window.location.href);
      // console.log(link)
      wechatLogin(link, 'wechat', localStorage.getItem('share_id'))
        .then((res) => {
          // return
          window.location.href = res.result;
        })
        .catch(function(error) {
          Toast(error.message);
        });
    },

    //获取用户信息
    // getMemberInfo(){
    //
    //     getMemberInfo().then(res=>{
    //         this.saveAuthInfo({token: this.token, info: res.result.member_info})
    //         this.goHome();
    //     });
    // }

    //微信登录
    // onWechat() {
    //     // let ref = encodeURIComponent(window.location.href)
    //     wechatLogin('','wechat',localStorage.getItem('share_id')).then(res => {
    //         // window.location.href = res.result
    //     }).catch(function (error) {
    //         Toast(error.message)
    //     })
    // }
    sendVerifyCodeMobile() {
      if (!this.username) {
        Toast('请先输入手机号');
        return;
      }
      if (!this.canSendMobile) {
        return;
      }
      getSmsCaptcha(2, this.username)
        .then((res) => {
          this.canSendMobile = false;
          let second = 60;
          Toast(res.message);
          let _this = this;
          this.timeIntervalMobile = setInterval(function() {
            if (second <= 0) {
              _this.canSendMobile = true;
              _this.sendStateTextMobile = '发送';
              clearInterval(_this.timeIntervalMobile);
            } else {
              _this.sendStateTextMobile = second + 's';
            }
            second--;
          }, 1000);
        })
        .catch(function(error) {
          Toast(error.message);
        });
    },
    switchLoginType(type) {
      this.login_type = type;
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  background-color: #f0f2f5;
  // height: calc(100vh - 50px);
  height: 100vh;

  .top-wrapper {
    .input-wrapper {
      display: flex;
      align-content: center;
      align-items: center;
      padding-left: 0.5rem;
      background-color: #fff;
      height: 2.2rem;

      img {
        width: 1.2rem;
        height: 1.2rem;
        margin: 0;
        padding: 0;
      }

      input {
        flex: 1;
        font-size: 0.8rem;
      }

      .bottom-input {
        border-bottom-width: 0;
      }
    }
  }
}

.wx-login {
  display: flex;
  flex-direction: column;
  align-items: center;

  .wx-img {
    width: 50px;
    height: 50px;
  }

  .wx-title {
    margin-top: 3px;
    font-size: 0.7rem;
    font-weight: bold;
    color: #999;
  }
}

.retrieve-wrapper {
  height: 2rem;
  margin-top: 0.5rem;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.retrieve-item {
  height: 2rem;
  margin: 0 0.5rem;
  display: flex;
  justify-content: center;
  align-items: center;
}

#retrieve-title {
  color: #3c7c45;
  font-size: 0.75rem;
  text-align: center;
}

.bottom-wrapper {
  display: flex;
  flex: 1;
  flex-direction: column;
  justify-content: flex-end;
  align-items: stretch;
}

.auth-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  height: 13rem;
}

.auth-title-wrapper {
  height: 1rem;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 2rem;
}

.auth-title {
  color: #8f8e94;
  font-size: 0.7rem;
}

.auth-line {
  display: flex;
  flex: 1;
  height: 1px;
  background-color: #d8d8d8;
  margin-left: 0.8rem;
  margin-right: 0.8rem;
}

.auth-item {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}

.auth-item-icon {
  width: 3rem;
  height: 3rem;
  text-align: center;
  font-size: 3rem;
}

.wechat {
  color: #2db304;
}

.sina {
  color: #f01414;
}

.tencent {
  color: #26a2ff;
}

.auth-item-title {
  margin-top: 0.6rem;
}

.auth-bottom-wrapper {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  margin-left: 0.75rem;
  margin-right: 0.75rem;
  margin-bottom: 1rem;
}
</style>
